package com.axend.aerosense.pay;

import android.app.Activity;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.android.billingclient.api.AcknowledgePurchaseParams;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingFlowParams;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.ConsumeParams;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.PurchaseHistoryRecord;
import com.android.billingclient.api.PurchaseHistoryResponseListener;
import com.android.billingclient.api.PurchasesResponseListener;
import com.android.billingclient.api.PurchasesUpdatedListener;
import com.android.billingclient.api.SkuDetails;
import com.android.billingclient.api.SkuDetailsParams;
import com.axend.aerosense.base.utils.LogUtils;

import java.util.ArrayList;
import java.util.List;

public class GooglePayClient {

    public static final int STATE_USER_CANCELED = 1;  //用户取消
    public static final int STATE_UNKNOWN_ERROR = 2;  //未知错误
    public static final int STATE_NETWORK_ERROR = 3;  //网络错误
    public static final int STATE_HISTORY_GOODS_ERROR = 4;  //历史商品处理（消费）错误
    public static final int STATE_REPEAT_SUBSCRIBE = 5;  //商品重复订阅（一个用户只能订阅一件商品）

    private final int maxConnectCount = 3;  //最大重新创建连接次数
    private int connectCount = 0;

    private BillingClient billingClient;
    private GooglePayConfig config;

    /*public static GooglePayClient getInstance(Activity activity){
        if (null == instance){
            synchronized (GooglePayClient.class){
                if (null == instance){
                    mActivity = activity;
                    instance = new GooglePayClient();
                }
            }
        }
        return instance;
    }*/

    public static Builder Builder() {
        return new Builder();
    }

    public static class Builder{
        GooglePayConfig config;

        private Builder(){
            config = new GooglePayConfig();
        }

        public Builder setActivity(@NonNull Activity activity){
            config.activity = activity;
            return this;
        }

        public Builder setSkuType(@NonNull SkuType skuType){
            config.skuType = skuType;
            return this;
        }

        public Builder setPurchaseId(@NonNull String purchaseId){
            config.purchaseId = purchaseId;
            return this;
        }

        public Builder setPayCallback(@NonNull PayCallback callback){
            config.payCallback = callback;
            return this;
        }

//        public Builder setUserId(@NonNull String userId){
//            config.userId = userId;
//            return this;
//        }

        public GooglePayClient build(){
            return new GooglePayClient(config);
        }
    }

    private GooglePayClient(GooglePayConfig config){
        //第一次创建，初始化
        this.config = config;
        init();
    }

    private void init(){
        billingClient = BillingClient.newBuilder(config.activity)
                .setListener(new PurchasesUpdatedListener() {
                    @Override
                    public void onPurchasesUpdated(@NonNull BillingResult billingResult, @Nullable List<Purchase> list) {
                        LogUtils.d(GooglePayClient.this, "onSkuDetailsResponse code = " + billingResult.getResponseCode() + " ,  msg = " + billingResult.getDebugMessage());
                        if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                            //支付成功
                            if (list != null && !list.isEmpty()){
                                //消费当前商品
                                handlePurchase(list, false);
                            }
                        }else if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.USER_CANCELED) {
                            //用户取消
                            LogUtils.d(GooglePayClient.this, "用户取消支付");
                            callbackError(STATE_USER_CANCELED);
                        }else {
                            //其他错误
                            LogUtils.d(GooglePayClient.this, "未知错误");
                            callbackError(STATE_UNKNOWN_ERROR);
                        }
                    }
                })
                .enablePendingPurchases()
                .build();
    }

    /**
     * billingClient是否已连接服务器，准备就绪
     * @return
     */
    private boolean isReady(){
        if (null != billingClient){
            return billingClient.isReady();
        }

        return false;
    }

    /**
     * 与谷歌支付服务器创建连接
     */
    private void createConnect(){
        if (null != billingClient && !isReady()){
            billingClient.startConnection(new BillingClientStateListener() {
                @Override
                public void onBillingServiceDisconnected() {
                    //服务连接失败
                    LogUtils.d(GooglePayClient.this, "onBillingServiceDisconnected(),  Google Play 建立连接失败");

                    //重新创建连接
                    if (connectCount < maxConnectCount){
                        createConnect();
                    }else {
                        //创建连接失败，回调到错误
                        callbackError(STATE_NETWORK_ERROR);
                    }
                    connectCount++;
                }

                @Override
                public void onBillingSetupFinished(@NonNull BillingResult billingResult) {
                    //服务连接成功
                    if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK){
                        LogUtils.d(GooglePayClient.this, "onBillingSetupFinished(),  Google Play 建立连接成功");
                        //在支付之前，查询未消耗的商品
                        queryHistory();
                    }else {
                        callbackError(STATE_NETWORK_ERROR);
                    }
                }
            });
        }else {
            LogUtils.e(this, "billingClient is Null");
        }
    }

    /**
     * 查询商品信息
     */
    private void queryPurchases(){
        List<String> skuList = new ArrayList<>();
        skuList.add(config.purchaseId);
        SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
        params.setSkusList(skuList)
                .setType(config.skuType.getSkuType());
        billingClient.querySkuDetailsAsync(params.build(),
                (billingResult, skuDetailsList) -> {
                    LogUtils.d(GooglePayClient.this, "onSkuDetailsResponse code = " + billingResult.getResponseCode() + " ,  msg = " + billingResult.getDebugMessage() + " , skuDetailsList = " + skuDetailsList);
                    if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK
                            && null != skuDetailsList
                            && !skuDetailsList.isEmpty()) {

                        if (skuDetailsList == null || skuDetailsList.isEmpty()){
                            callbackError(STATE_UNKNOWN_ERROR);
                            new Throwable("Goods list is Null!");
                            return;
                        }
                        for (SkuDetails details : skuDetailsList){
                            LogUtils.d(GooglePayClient.this, details.toString());
                            LogUtils.d(GooglePayClient.this, "getSku:" + details.getSku());
                            if (config.purchaseId.equals(details.getSku())){
                                //用户购买的商品ID跟服务器返回的商品ID一致，则进行下一步支付操作
                                pay(details);
                                //break;
                            }
                        }
                    }else {
                        callbackError(STATE_NETWORK_ERROR);
                    }
                });
    }

    /**
     * 查询商品消费状态（在缓存中查找）
     * 此方法会返回已订阅的商品（"autoRenewing":true,"acknowledged":true字段都为true）
     */
    private void queryHistory(){
        if (null != billingClient){
            //仅返回有效订阅和未消费的一次性购买
            billingClient.queryPurchasesAsync(config.skuType.getSkuType(), new PurchasesResponseListener() {
                @Override
                public void onQueryPurchasesResponse(@NonNull BillingResult billingResult, @NonNull List<Purchase> list) {
                    LogUtils.d(GooglePayClient.this, "查询历史商品，onQueryPurchasesResponse():" + list);
                    if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {

                        if (null != billingResult && null != list && !list.isEmpty()) {
                            //未消费的的商品
                            List<Purchase> consumeList = new ArrayList<>();
                            for (Purchase purchase : list) {
                                com.blankj.utilcode.util.LogUtils.d("PurchaseState:" + purchase.getPurchaseState(),
                                        "isAcknowledged:" + purchase.isAcknowledged(), "isAutoRenewing:" + purchase.isAutoRenewing());
                                //商品是否已购买
                                if (purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED) {
                                    consumeList.add(purchase);
                                }
                            }

                            if (!consumeList.isEmpty()){
                                //消耗历史未消耗的商品
                                if (config.skuType == SkuType.SUBS){
                                    //订阅商品需检查是否重复订阅
                                    checkRepeatSubscribe(consumeList);
                                }else {
                                    handlePurchase(consumeList, true);
                                }
                            }else {
                                //没有未消耗的商品，执行下一步
                                queryPurchases();
                            }

                        } else {
                            //没有未消耗的商品，执行下一步
                            queryPurchases();
                        }
                    } else {
                        callbackError(STATE_HISTORY_GOODS_ERROR);
                    }
                }
            });
        }else {
            LogUtils.e(this, "billingClient is Null");
        }
    }

    /**
     * 在谷歌服务器中查找最近的订单信息（不能查询订单支付状态）
     */
    private void queryHistoryByGoogleServer(){
        if (null == billingClient){
            LogUtils.e(this, "billingClient is Null");
            return;
        }
        billingClient.queryPurchaseHistoryAsync(config.skuType.getSkuType(), new PurchaseHistoryResponseListener() {
            @Override
            public void onPurchaseHistoryResponse(@NonNull BillingResult billingResult, @Nullable List<PurchaseHistoryRecord> list) {
                if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK){
                    com.blankj.utilcode.util.LogUtils.d("List<PurchaseHistoryRecord>:" + list);
                }else {
                    callbackError(STATE_HISTORY_GOODS_ERROR);
                }
            }
        });
    }

    /**
     * 检查历史订阅商品中是否进行重复订阅，如果有多个未消费的订阅商品，则剔除其他的，只保留第一个
     * @param consumeList
     * @return
     */
    private void checkRepeatSubscribe(List<Purchase> consumeList){
        if (null == consumeList || consumeList.isEmpty()){
            com.blankj.utilcode.util.LogUtils.e("consumeList is Null!");
            callbackError(STATE_HISTORY_GOODS_ERROR);
            return;
        }
        for (int i = 0; i < consumeList.size(); i++){
            Purchase p = consumeList.get(i);
            if (p.isAcknowledged() && p.isAutoRenewing()){
                //有成功续订的，直接回调，不再进行下一步操作
                callbackError(STATE_REPEAT_SUBSCRIBE);
                return;
            }else if (!p.isAcknowledged() && p.isAutoRenewing()){
                //付款但未消费的（如果有多个未消费的订阅商品，则剔除其他的，只保留第一个）
                List<Purchase> temp = new ArrayList<>();
                temp.add(p);
                handlePurchase(temp, true);
                return;
            }else if (p.isAcknowledged() && !p.isAutoRenewing()){
                //用户手动取消订阅，不处理，可直接进行下一步
                queryPurchases();
                return;
            } else {
                //未知错误
                callbackError(STATE_HISTORY_GOODS_ERROR);
            }
        }
    }

    /**
     * 支付操作
     */
    private synchronized void pay(SkuDetails skuDetails){
        if (null != billingClient){
            BillingFlowParams flowParams = BillingFlowParams.newBuilder()
                    .setSkuDetails(skuDetails)
                    //.setObfuscatedAccountId(config.userId)  //此处可传入用户ID
                    //.setObfuscatedProfileId("orderId-123456-789")   //此处需要传入app服务器生成的订单ID
                    .build();

            int code = billingClient.launchBillingFlow(config.activity, flowParams).getResponseCode();
            if (code != BillingClient.BillingResponseCode.OK){
                //调起支付失败
                callbackError(STATE_UNKNOWN_ERROR);
            }
        }else {
            LogUtils.e(this, "billingClient is Null");
        }
    }

    /**
     * 消费商品
     * 注意：如果不执行，则自动退款
     * @param purchaseList
     * @param isHistoryGoods  是否为历史未消耗的商品
     */
    private synchronized void handlePurchase(List<Purchase> purchaseList, boolean isHistoryGoods) {
        if (null == purchaseList && purchaseList.isEmpty()){
            com.blankj.utilcode.util.LogUtils.e("Purchase is Null");
            return;
        }
        for (Purchase purchase : purchaseList){
            //商品是否得到购买
            if (purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED){
                //普通商品
                if (config.skuType == SkuType.INAPP){
                    LogUtils.d(this, "普通商品消耗");
                    ConsumeParams consumeParams = ConsumeParams.newBuilder()
                            .setPurchaseToken(purchase.getPurchaseToken())
                            .build();

                    billingClient.consumeAsync(consumeParams, (billingResult, s) -> {
                        LogUtils.d(GooglePayClient.this, "onConsumeResponse():  " + s);
                        if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK){
                            //消费成功
                            callbackSuccess(isHistoryGoods, purchase.getOriginalJson());
                            LogUtils.d(GooglePayClient.this, "普通商品消费成功！");
                        }else {
                            callbackError(isHistoryGoods ? STATE_HISTORY_GOODS_ERROR : STATE_NETWORK_ERROR);
                        }
                    });

                }else if (config.skuType == SkuType.SUBS){
                    LogUtils.d(this, "订阅商品消耗");
                    AcknowledgePurchaseParams acknowledgePurchaseParams =
                            AcknowledgePurchaseParams.newBuilder()
                                    .setPurchaseToken(purchase.getPurchaseToken())
                                    .build();

                    billingClient.acknowledgePurchase(acknowledgePurchaseParams, billingResult -> {
                        if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK){
                            //消费成功
                            callbackSuccess(isHistoryGoods, purchase.getOriginalJson());
                            LogUtils.d(GooglePayClient.this, "订阅商品消费成功！");
                        }else {
                            callbackError(isHistoryGoods ? STATE_HISTORY_GOODS_ERROR : STATE_NETWORK_ERROR);
                        }
                    });

                }
            }else {
                //商品未购买与交易
                callbackError(STATE_UNKNOWN_ERROR);
            }
        }

        //如果是历史订单，消耗完成进行新的订单购买流程
        if (isHistoryGoods){
            queryPurchases();
        }
    }

    private void callbackSuccess(boolean isHistoryGoods, String purchaseJson){
        if (null != config.payCallback && null != purchaseJson && purchaseJson.length() > 0){
            config.payCallback.paySuccess(isHistoryGoods, purchaseJson);
        }else {
            com.blankj.utilcode.util.LogUtils.e( "PayCallback || PurchaseJson is Null!");
        }

        if (!isHistoryGoods){
            //非历史商品回调，则关闭连接
            close();
        }
    }

    private void callbackError(int state){
        if (null != config.payCallback){
            config.payCallback.payError(state);
        }else {
            com.blankj.utilcode.util.LogUtils.e( "PayCallback is Null!");
        }

        if (state == STATE_USER_CANCELED
                || state == STATE_REPEAT_SUBSCRIBE
                || state == STATE_UNKNOWN_ERROR
                || state == STATE_NETWORK_ERROR){
            close();
        }
    }

    /**
     * 查询商品并进行支付
     */
    public void queryPurchaseAndPay(){
        if (!TextUtils.isEmpty(config.purchaseId)
                && null != config.skuType
                && null != config.activity){

            createConnect();

        }
    }

    /**
     * 使用完成请释放资源
     */
    private void close(){
        LogUtils.d(this, "关闭连接");
        //结束连接
        billingClient.endConnection();
        config = null;
        billingClient = null;
    }

}
